<?php

namespace System\Lib\Twitter\Auth;

/**
 * Description of Request
 *
 * @author Elton Schivei Costa
 */
class Request
{

    private $_parameters;
    private $_httpMethod;
    private $_httpUrl;
    // for debug purposes
    public $baseString;
    public static $Version = '1.0';
    public static $POST_INPUT = 'php://input';

    function __construct($http_method, $http_url, Array $parameters = NULL)
    {
        $parameters = $parameters ? : array();
        $parameters = \array_merge(Util::parse_parameters(\parse_url($http_url, \PHP_URL_QUERY)), $parameters);
        $this->_parameters = $parameters;
        $this->_httpMethod = $http_method;
        $this->_httpUrl = $http_url;
    }

    /**
     * attempt to build up a request from what was passed to the server
     */
    public static function FromRequest($http_method = NULL, $http_url = NULL, $parameters = NULL)
    {
        $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
        @$http_url or $http_url = $scheme .
                '://' . $_SERVER['HTTP_HOST'] .
                ':' .
                $_SERVER['SERVER_PORT'] .
                $_SERVER['REQUEST_URI'];
        @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];

        // We weren't handed any parameters, so let's find the ones relevant to
        // this request.
        // If you run XML-RPC or similar you should use this to provide your own
        // parsed parameter-list
        if (!$parameters)
        {
            // Find request headers
            $request_headers = Util::get_headers();

            // Parse the query-string to find GET parameters
            $parameters = Util::parse_parameters($_SERVER['QUERY_STRING']);

            // It's a POST request of the proper content-type, so parse POST
            // parameters and add those overriding any duplicates from GET
            if ($http_method == "POST"
                    && @\strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded")
            )
            {
                $post_data = Util::parse_parameters(
                                \file_get_contents(self::$POST_INPUT)
                );
                $parameters = \array_merge($parameters, $post_data);
            }

            // We have a Authorization-header with OAuth data. Parse the header
            // and add those overriding any duplicates from GET or POST
            if (@\substr($request_headers['Authorization'], 0, 6) == "OAuth ")
            {
                $header_parameters = Util::split_header(
                                $request_headers['Authorization']
                );
                $parameters = \array_merge($parameters, $header_parameters);
            }
        }

        return new self($http_method, $http_url, $parameters);
    }

    /**
     * pretty much a helper function to set up the request
     */
    public static function FromConsumerAndToken($consumer, $token, $http_method, $http_url, $parameters = NULL)
    {
        @$parameters or $parameters = array();
        $defaults = array("oauth_version" => self::$version,
            "oauth_nonce" => self::GenerateNonce(),
            "oauth_timestamp" => self::GenerateTimestamp(),
            "oauth_consumer_key" => $consumer->key);
        if ($token)
            $defaults['oauth_token'] = $token->key;

        $parameters = \array_merge($defaults, $parameters);

        return new self($http_method, $http_url, $parameters);
    }

    public function set_parameter($name, $value, $allow_duplicates = true)
    {
        if ($allow_duplicates && isset($this->_parameters[$name]))
        {
            // We have already added parameter(s) with this name, so add to the list
            if (\is_scalar($this->_parameters[$name]))
            {
                // This is the first duplicate, so transform scalar (string)
                // into an array so we can add the duplicates
                $this->_parameters[$name] = array($this->_parameters[$name]);
            }

            $this->_parameters[$name][] = $value;
        }
        else
        {
            $this->_parameters[$name] = $value;
        }
    }

    public function GetParameter($name)
    {
        return isset($this->_parameters[$name]) ? $this->_parameters[$name] : null;
    }

    public function GetParameters()
    {
        return $this->_parameters;
    }

    public function UnsetParameter($name)
    {
        unset($this->_parameters[$name]);
    }

    /**
     * The request parameters, sorted and concatenated into a normalized string.
     * @return string
     */
    public function GetSignableParameters()
    {
        // Grab all parameters
        $params = $this->_parameters;

        // Remove oauth_signature if present
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
        if (isset($params['oauth_signature']))
        {
            unset($params['oauth_signature']);
        }

        return Util::build_http_query($params);
    }

    /**
     * Returns the base string of this request
     *
     * The base string defined as the method, the url
     * and the parameters (normalized), each urlencoded
     * and the concated with &.
     */
    public function GetSignatureBaseString()
    {
        $parts = array(
            $this->GetNormalizedHttpMethod(),
            $this->GetNormalizedHttpUrl(),
            $this->GetSignableParameters()
        );

        $parts = Util::urlencode_rfc3986($parts);

        return \implode('&', $parts);
    }

    /**
     * just uppercases the http method
     */
    public function GetNormalizedHttpMethod()
    {
        return \strtoupper($this->_httpMethod);
    }

    /**
     * parses the url and rebuilds it to be
     * scheme://host/path
     */
    public function GetNormalizedHttpUrl()
    {
        $parts = \parse_url($this->_httpUrl);

        $port = @$parts['port'];
        $scheme = $parts['scheme'];
        $host = $parts['host'];
        $path = @$parts['path'];

        $port or $port = ($scheme == 'https') ? '443' : '80';

        if (($scheme == 'https' && $port != '443')
                || ($scheme == 'http' && $port != '80'))
        {
            $host = "$host:$port";
        }
        return "$scheme://$host$path";
    }

    /**
     * builds a url usable for a GET request
     */
    public function ToUrl()
    {
        $post_data = $this->ToPostdata();
        $out = $this->GetNormalizedHttpUrl();
        if ($post_data)
        {
            $out .= '?' . $post_data;
        }
        return $out;
    }

    /**
     * builds the data one would send in a POST request
     */
    public function ToPostdata()
    {
        return Util::build_http_query($this->_parameters);
    }

    /**
     * builds the Authorization: header
     */
    public function ToHeader($realm = null)
    {
        $first = true;
        if ($realm)
        {
            $out = 'Authorization: OAuth realm="' . Util::urlencode_rfc3986($realm) . '"';
            $first = false;
        } else
            $out = 'Authorization: OAuth';

        foreach ($this->_parameters as $k => $v)
        {
            if (\substr($k, 0, 5) != "oauth")
                continue;
            if (\is_array($v))
            {
                throw new AuthException('Arrays not supported in headers');
            }
            $out .= ($first) ? ' ' : ',';
            $out .= Util::urlencode_rfc3986($k) .
                    '="' .
                    Util::urlencode_rfc3986($v) .
                    '"';
            $first = false;
        }
        return $out;
    }

    public function ToString()
    {
        return $this->ToUrl();
    }

    public function SignRequest($signature_method, $consumer, $token)
    {
        $this->set_parameter(
                "oauth_signature_method", $signature_method->get_name(), false
        );
        $signature = $this->BuildSignature($signature_method, $consumer, $token);
        $this->set_parameter("oauth_signature", $signature, false);
    }

    public function BuildSignature($signature_method, $consumer, $token)
    {
        $signature = $signature_method->BuildSignature($this, $consumer, $token);
        return $signature;
    }

    /**
     * util function: current timestamp
     */
    private static function GenerateTimestamp()
    {
        return \time();
    }

    /**
     * util function: current nonce
     */
    private static function GenerateNonce()
    {
        $mt = \microtime();
        $rand = \mt_rand();

        return \md5($mt . $rand); // md5s look nicer than numbers
    }

}

